#ifndef NETWORKMANAGER_H
#define NETWORKMANAGER_H

#include "NetworkTask.h"
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QQueue>
#include <QMap>
#include <QMutex>
#include <QTimer>

class NetworkManager : public QObject {
    Q_OBJECT

public:
    explicit NetworkManager(QObject* parent = nullptr);
    ~NetworkManager();

    // 设置服务器基础URL
    void setServerUrl(const QString& url);

    // 设置超时时间（毫秒）
    void setTimeout(int milliseconds);

    // 设置最大并发请求数
    void setMaxConcurrentRequests(int maxCount);

    // 发送请求（异步）
    template<typename RequestType, typename ResponseType>
    int sendRequest(const RequestType& request, ResponseType* response);

    template<typename RequestType,typename ResponseType>
    bool sendRequestSync(const RequestType& request,ResponseType* response);

    // 取消指定任务
    void cancelTask(int taskId);

    // 取消所有任务
    void cancelAllTasks();

signals:
    // 请求完成信号
    void requestCompleted(int taskId, bool success, const QString& error);

    // 网络错误信号
    void networkError(int taskId, const QString& errorString);

private slots:
    void onRequestFinished(QNetworkReply* reply);
    void onRequestTimeout();
    void processNextTask();

private:
    void sendHttpPost(NetworkTask* task);
    int generateTaskId();
    void cleanupTask(int taskId);

private:
    QNetworkAccessManager* m_networkManager;
    QString m_serverUrl;
    int m_timeout;
    int m_maxConcurrent;
    int m_currentTaskId;

    QQueue<NetworkTask*> m_taskQueue;
    QMap<int, NetworkTask*> m_runningTasks;
    QMap<QNetworkReply*, int> m_replyToTaskMap;
    QMap<int, QTimer*> m_taskTimers;

    QMutex m_mutex;
};


// 模板方法实现
template<typename RequestType, typename ResponseType>
int NetworkManager::sendRequest(const RequestType& request, ResponseType* response) {
    QMutexLocker locker(&m_mutex);

    int taskId = generateTaskId();
    BaseRequest* req = new RequestType(request);
    NetworkTask* task = new NetworkTask(req, response, taskId);

    m_taskQueue.enqueue(task);


    // 如果当前运行的任务数小于最大并发数，立即处理
    if (m_runningTasks.size() < m_maxConcurrent)
    {
        QTimer::singleShot(0, this, &NetworkManager::processNextTask);
    }


    return taskId;
}


template<typename RequestType,typename ResponseType>
bool NetworkManager::sendRequestSync(const RequestType& request,ResponseType* response)
{
    QMutexLocker locker(&m_mutex);
    int taskId = generateTaskId();
    BaseRequest* req = new RequestType(request);
    NetworkTask* task = new NetworkTask(req,response,taskId);

}


#endif // NETWORKMANAGER_H
